package com.mmall.concurrency.example.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.StampedLock;

@Slf4j
public class ConditionExample1 {

    public static void main(String[] args) {
        final ReentrantLock reentrantLock = new ReentrantLock();
        final  StampedLock stampedLock = new StampedLock();
        final Condition condition = reentrantLock.newCondition();

        new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLock.lock();
                System.out.println(Thread.currentThread().getName() + "拿到锁了");
                System.out.println(Thread.currentThread().getName() + "等待信号");
                try {
                    // 此线程被阻塞在这里，等待唤醒
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 被唤醒后才会执行以下的代码
                System.out.println(Thread.currentThread().getName() + "拿到信号");

                reentrantLock.unlock();
            }
        }, "线程1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                long stamp = stampedLock.writeLock();
                System.out.println(Thread.currentThread().getName() + "拿到锁了");
                System.out.println(Thread.currentThread().getName() + "等待信号");
                try {
                    // 此线程被阻塞在这里，等待唤醒
                    condition.await();
                    System.out.println(Thread.currentThread().getName() + "继续执行");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 被唤醒后才会执行以下的代码
                System.out.println(Thread.currentThread().getName() + "拿到信号");

                stampedLock.unlock(stamp);
            }
        }, "线程2").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLock.lock();
                System.out.println(Thread.currentThread().getName() + "拿到锁了");

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + "发出信号");
                // 唤醒被reentrantLock锁阻塞的线程，是明确指定了被唤醒的线程与reentrantLock有关，其他锁线程不会被唤醒
                condition.signalAll();

                reentrantLock.unlock();
            }
        }, "线程3").start();
    }
}
